package org.zoomdev.zoom.server.modules;

import org.zoomdev.zoom.web.ExceptionHandler;
import org.zoomdev.zoom.web.action.ActionHandler;
import org.zoomdev.zoom.web.handlers.NotFoundFilterHandler;
import org.zoomdev.zoom.web.router.Router;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

final class InnerFilter implements Filter {

    private final Router router;
    private final NotFoundFilterHandler notFoundHandler;

    private final ExceptionHandler exceptionHandler;

    public InnerFilter(Router router, NotFoundFilterHandler notFoundHandler, ExceptionHandler exceptionHandler) {
        this.router = router;
        this.notFoundHandler = notFoundHandler;
        this.exceptionHandler = exceptionHandler;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        try {
            ActionHandler handler = router.match(request);
            if (handler == null) {
                notFoundHandler.handle(request, response, chain);
                return;
            }
            handler.handle(request, response);
        } catch (Throwable e) {
            exceptionHandler.handle(request, response, e);
        }
    }

    @Override
    public void destroy() {

    }
}
